<template>
  <div class="flexMainBetween row2">
    <!-- 类型 -->
    <div class="tabs">
      <div :class="['tab', { 'act': activeType == item.id }]" v-for="item in typeList" :key="item.id"
        @click="changeType(item.id)">
        <p>{{ item.name }}</p>
        <div class="act_line"></div>
      </div>
    </div>
    <van-button color="#fff7eb" class="btn-computer" @click="redirect('/calculator','计算器')">
      <template #icon><img src="@/assets/img/icon-computer.png"></template>
      计算器
    </van-button>
  </div>
  <van-divider />
  <van-tabs v-model:active="active" animated swipeable class="tabs2" line-height="0" @change="beforeChange" lazy-render>
    <van-tab v-for="(item, i) in dateList" :key="item.id">
      <template #title>
        <!-- 传足内参 -->
        <div :class="['tab_tit', { 'act': active == i }]" v-if="isTradition">{{ item.issue_num }}</div>
        <!-- 足、篮内参 -->
        <div class="tab_tit flexCenter" v-else>
          <div class="numBox" v-if="active == i">{{ item.total_num }}场</div>
          <div class="zhongBox r" v-else-if="item.hit_rate >= 60">
            {{ item.finished_num + "中" + item.hit_num }}
          </div>
          <div class="zhongBox g" v-else-if="item.total_num">{{ item.total_num }}场</div>
          <div class="holder" v-else></div>
          <p :class="['date', { 'act': active == i }]">{{ transDateWeek(item.wtime) }}</p>
        </div>
      </template>
      <!-- 列表 -->
      <van-list v-if="active==i" v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <div class="panel" v-for="item in art.matchList" :key="item.id" @click="gotoDetail(item)">
          <div class="flexMainBetween">
            <p class="secondary">
              <span class="weekNo" v-if="item.session">{{ item.session }}</span>
              <span class="weekNo" v-else>{{ item.week }}{{ item.week_no }}</span>
              <span>{{ format(item.stime * 1000, "HH:mm") }}&nbsp;{{ item.cup }}</span>
            </p>
            <!-- 足球显示半场比分 -->
            <p class="half" v-if="isFootBall&&item.status != 0">半:{{activeType == 2 ?
              (item.guest_half+"-"+item.home_half)
              : (item.home_half+"-"+item.guest_half)}}</p>
            <img src="@/assets/img/single.png" class="single" v-if="item.single">
          </div>
          <!-- 异常 -->
          <div class="status" v-if="item.match_status == 0">异常</div>
          <!-- 未开赛 -->
          <div class="status" v-else-if="item.match_status==1">未</div>
          <!-- 完场 足球8 篮球10 -->
          <div class="status"
            v-else-if="(isFootBall && item.match_status == 8) || (item.types == 2 && item.match_status == 10)">完
          </div>
          <template v-if="isFootBall">
            <!-- 进行中 足球大于1小于8 -->
            <div class="status living" v-if="item.match_status > 1 && item.match_status < 8">
              <!-- {{ footProgressTrans(item.match_status) }} -->
              {{ item.minute }}
              <span class="twinkle">′</span>
            </div>
            <!-- 其他 大于8 -->
            <div class="status" v-else-if="item.match_status > 8">
              {{ footOtherStatus(item.match_status) }}
            </div>
          </template>
          <template v-else-if="item.types == 2">
            <!-- 进行中 篮球大于1小于10 -->
            <div class="status living" v-if="item.match_status > 1 && item.match_status < 10">
              {{ basketProgressTrans(item.match_status) }}
              {{ item.minute }}
            </div>
            <!-- 其他 大于10 -->
            <div class="status" v-else-if="item.match_status > 10">
              {{ basketOtherStatus(item.match_status) }}
            </div>
          </template>
          <div :class="['mainInfo', 'flexCenter', { 'reverse': activeType == 2, 'center': isTradition && !item.p_spf}]">
            <div class="left flexCrossCenter">
              <span class="rank" v-if="item.home_position">[{{ removeChinese(item.home_position) }}]</span>
              <span class="teamName">{{ item.home }}</span>
              <van-image class="icon" v-if="item.h_icon" :src="`${globe.staticDomain}/${item.h_icon}`" fit="contain" />
              <van-image class="icon" v-else :src="match_home_default" fit="contain" />
            </div>
            <div class="score flexCenter b" v-if="item.match_status == 1">
              <span class="iconfont iconfont-duizhan"></span>
            </div>
            <div class="score flexCenter r" v-else>
              {{ activeType == 2 ? (item.guest_full + "-" + item.home_full) : (item.home_full + "-" + item.guest_full)
              }}</div>
            <div class="right flexCrossCenter">
              <van-image class="icon" v-if="item.g_icon" :src="`${globe.staticDomain}/${item.g_icon}`" fit="contain" />
              <van-image class="icon" v-else :src="match_guest_default" fit="contain" />
              <span class="teamName">{{ item.guest }}</span>
              <span class="rank" v-if="item.guest_position">[{{ removeChinese(item.guest_position) }}]</span>
            </div>
          </div>
          <!-- 传足预测 -->
          <div class="playMethods tradition" v-if="item.p_spf">
            <van-button :class="['btn', ['', pm].includes(item.spf) ? 'b-red':'b-gray'] "
              v-for="(pm, i) in item.p_spf.split(',')" :key="i">
              {{ czflags[pm] }}
              <template v-if="item.spf == pm">
                <div class="angle"></div>
                <van-icon name="success" class="check" color="#FF3B3B" />
              </template>
            </van-button>
          </div>
          <!-- 足球、篮球玩法 -->
          <div class="playMethods default" v-else-if="!isTradition">
            <template v-if="item.status == 1">
              <van-button class="btn b-red" v-if="item.result" v-for="(p, i) in item.result.split(',')" :key="i">
                <template v-for="(pm, i) in item[`p_${p}`].split(',')">
                  <template v-if="i == 1">/</template>{{ playRes[p == 'hdc' ? `${p}_${pm}` : pm] }}
                </template>
                <div class="angle"></div>
                <van-icon name="success" class="check" color="#FF3B3B" />
              </van-button>
            </template>
            <template v-else v-for="p in pmArr" :key="p.key">
              <van-button :class="['btn', 'b-pink']" v-if="item[p.key]">
                <template v-for="(pm, i) in item[p.key].split(',')">
                  <template v-if="i == 1">/</template>{{ playRes[p.en == 'hdc' ? `${p.en}_${pm}` : pm] }}
                </template>
              </van-button>
            </template>
            <div class="viewFx">
              <span>查看分析</span>
              <van-icon name="arrow" class="arrowRight" />
            </div>
          </div>
        </div>
      </van-list>
    </van-tab>
  </van-tabs>
</template>

<script setup>
import { dataList } from '@/api/calc'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore, useGlobeStore, useArtStore } from "@/stores";
import { getWeek } from '@/utils/calc'
import { format, startOfDay } from 'date-fns';
import { footballPm, basktballPm, playRes } from '@/utils/data'
import { footProgressTrans, footOtherStatus, basketProgressTrans, basketOtherStatus } from '@/utils/helper'
import { useMqtt } from '@/hooks/mqtt'
import match_guest_default from '@/assets/image/shopColorTools/match_guest_default.png'
import match_home_default from '@/assets/image/shopColorTools/match_home_default.png'

const mqtt = useMqtt();
const user = useUserStore();
const globe = useGlobeStore();
const art = useArtStore();
const router = useRouter();
const route = useRoute();
const typeList = [
  { id: 0, name: "足球", type: "football", long_link: 'match/football/jc' },
  { id: 1, name: "传足", type: "tradition", long_link: 'match/cz' },
  { id: 2, name: "篮球", type: "basketball", long_link: 'match/basketball/jc' },
]
const activeType = ref(0);
const dateList = ref([]); // 日期列表
const active = ref(-1); // 选中的日期索引
const loading = ref(false);
const finished = ref(false);
const isTradition = computed(() => activeType.value == 1);
const isFootBall = computed(() => activeType.value < 2);
const wtime = computed(() =>{
  if (dateList.value.length > 0){
    return isTradition.value
      ? dateList.value[active.value].issue_num
      : dateList.value[active.value].wtime;
  }else{
    return 0
  }
})
const selectType = computed(() => typeList[activeType.value].type)
// const resflags = { 'had': '胜平负', 'hhad': '让胜平负', 'crs': '比分', 'ttg': '总进球', 'hafu': '半全场', 'mnl': '胜负', 'hdc': '让胜负', 'hilo': '大小分', 'wnm': '胜分差', 'spf': '310' }
const czflags = { "spf1": "1", "spf0": "0", "spf3": "3" }
const pmArr = computed(() => {
  if (activeType.value == 0) return footballPm;
  else if (activeType.value == 2) return basktballPm;
  else return null;
})

function hasHit(result, pm){
  if (result){
    const arr = result.split(',')
    return arr.some(str => `p_${str}` == pm);
  }else{
    return false;
  }
}

function redirect(path, label){
  router.push(path);
  user.log({ type: 'event', action: 'click', opt_label: label, target_url: path});
}

function transDateWeek(time) {
  if (!time) return;
  const millsecond = time * 1000;
  const todayStart = startOfDay(new Date()).getTime();
  const week = (millsecond == todayStart) ? '今' : getWeek(new Date(millsecond), '');
  return format(millsecond, "MM·dd") + ' ' + week;
}

function removeChinese(str){
  return str.replace(/[\u4E00-\u9FFF]/g, '');
}
const onLoad = () => {
  // 异步更新数据
  art.queryMatchs({
    cid: globe.cid,
    type: selectType.value,
    i: user.i,
    version: 2,
    wtime: wtime.value,
    log: 1,
    token: route.query.token,
  }).finally(() => {
    // 加载状态结束
    loading.value = false;
    // 数据全部加载完成
    finished.value = true;
  })
};
async function getTabsData(){
  if (!user.i) return;
  if (active.value>-1) return;
  const res = await dataList({ day: 10, type: selectType.value, i: user.i, version: 2 })
  if(!res || res.length==0) return;
  if (isTradition.value){
    // 传足
    active.value = res.length - 1;
  }else{
    // 足球、篮球
    const todayStart = startOfDay(new Date());
    const timestamp = Math.floor(todayStart.getTime() / 1000);
    const index = res.findIndex(item => item.wtime == timestamp);
    if (index > -1) {
      active.value = index; // 更新当前选中的日期
    } else {
      const arr = res.filter(item => item.wtime < timestamp);
      if (arr.length > 0) {
        active.value = arr.length - 1; // 更新当前选中的日期
      }else{
        active.value = 0;
      }
    }
  }
  dateList.value = res;
}
// 更换类型
async function changeType(id) {
  if (activeType.value == id) return;
  activeType.value = id;
  // 重置数据
  active.value = -1;
  dateList.value = [];
  art.clearMatchList();
  await getTabsData();
  onLoad();
  // 更改订阅
  mqtt.reSubscrobe(typeList[activeType.value].long_link);
  // 记录日志
  user.log({ type: 'event', action: 'click', opt_label: typeList[activeType.value].name, target_url: '/match' });
}
// 更换时间
function beforeChange(i) {
  if (!wtime.value) return;
  onLoad();
}
function gotoDetail(item){
  const path = `/mdetail/${selectType.value}/${item.id}`;
  router.push(path);
  user.log({ type: 'event', action: 'click', opt_label: `${selectType.value}赛事详情`, target_url: path, data_id: item.id });
}
function connectMqtt(){
  if (art.token) {
    const { long_link } = typeList[activeType.value];
    mqtt.createConnection(long_link, art.token, (topic, data) => {
      // 列表有数据再更新
      if (art.matchList.length > 0){
        art.updateMatchList(data);
      }
    });
  }
}
watch(() => art.token, connectMqtt)
onActivated(()=>{
  connectMqtt();
  getTabsData();
})
onBeforeMount(()=>{
  art.getWsToken();
  art.clearMatchList();
})
onDeactivated(() => {
  mqtt.destroyConnection();
})
</script>

<style lang="less" scoped>
@import "@/assets/varables.less";
.row2 {
  padding-right: 16px;
  background-color: #fff;
}

.tabs {
  display: flex;
  color: #1D2129;
  font-size: 15px;

  .tab {
    padding: 16px 20px;
    position: relative;
  }

  p {
    position: relative;
    z-index: 1;
    line-height: 14px;
  }

  .act_line {
    width: 40px;
    height: 4px;
    position: absolute;
    bottom: 14px;
    z-index: 0;
  }

  .act {
    p {
      font-size: 16px;
      font-weight: 900;
    }

    .act_line {
      background: linear-gradient(90deg, #ffb752 0%, #ffb75200 100%);
    }
  }
}

.btn-computer {
  width: 70px;
  height: 30px;
  color: @prime1!important;
  font-size: 12px;

  img {
    display: block;
    width: 16px;
  }
}

.tabs2 {
  --van-tabs-line-height: 48px;
  :deep(.van-tab__text){
    display: block;
  }

  .tab_tit {
    flex-direction: column;
  }

  .holder{
    height: 16px;
  }

  .zhongBox {
    font-size: 10px;
    line-height: 1;
    border-top-left-radius: 7px;
    border-top-right-radius: 7px;
    border-bottom-right-radius: 7px;
    padding: 3px;
    &.r{
      background: #fff0f0;
      color: #FF2929;
    }
    &.g{
      color: #ADADAD;
      // color: #86909C;
      // border: 1px solid #86909C;
    }
  }

  .numBox {
    font-size: 10px;
    line-height: 1;
    color: #141414;
    // color: #fff;
    // background-color: #FF2929;
    border-radius: 7px;
    padding: 3px;
  }

  .date {
    margin-top: 4px;
    font-size: 14px;
    line-height: 1;
    color: #ADADAD;
  }

  .con {
    color: #141414;
  }
  .act {
    font-weight: 900;
    color: #141414!important;
  }
}

.panel {
  width: 359px;
  min-height: 100px;
  border-radius: 12px;
  background-color: #fff;
  border: 1px solid #ffffff;
  margin: 10px auto 0;
  padding: 8px 10px 0;
  position: relative;
  overflow: hidden;

  .secondary {
    font-size: 12px;
    color: #ADADAD;
  }

  .weekNo {
    color: #ADADAD;
    margin-right: 4px;
  }

  .single {
    width: 20px;
  }

  .half{
    font-size: 11px;
    color: #86909C;
    position: absolute;
    top: 8px;
    left: 210px;
  }

  .status {
    position: absolute;
    top: 8px;
    left: 50%;
    transform: translateX(-50%);
    min-width: 32px;
    height: 20;
    line-height: 20px;
    padding: 0 10px;
    font-size: 11px;
    border-radius: 10px;
    background-color: #F5F5F5;
    color: #ADADAD;
    &.living{
      background: #fff4f3;
      color: #F96235;
    }
  }

  @keyframes blink{
    0%{
      opacity: 1;
    }
    50% {
      opacity: 0;
    }
    100% {
      opacity: 1;
    }
  }
  .twinkle{
    animation: blink 1s linear infinite;
    font-size: 12px;
  }
  .mainInfo {
    width: 100%;
    margin: 16px 0 12px;
    &.center{
      margin-top: 22px;
    }
    &.reverse{
      flex-direction: row-reverse!important;
      .left,.right{
        flex-direction: row-reverse !important;
      }
    }

    .rank {
      color: #ADADAD;
      font-size: 10px;
    }

    .teamName {
      color: #141414;
      font-size: 12px;
      line-height: 1;
      font-weight: 700;
      margin: 0 4px;
      word-break: break-all;
    }

    .icon {
      width: 24px;
      height: 24px;
      margin: 0 4px;
    }

    .left,
    .right {
      flex: 1;
    }

    .left {
      justify-content: flex-end;

      .teamName {
        text-align: right;
      }
    }

    .score {
      min-width: 40px;
      font-size: 16px;
      line-height: 1;
      font-weight: 900;
      margin: 0 4px;
      &.baskt {
        width: 90px;
        margin: 0 !important;
      }
      &.b {
        color: #141414;
      }
      &.r{
        color: #FF5252;
      }
    }
  }

  .playMethods {
    display: flex;
    --van-button-normal-padding: 0 8px;
    --van-button-border-width: 0;
    &.default{
      margin: 0 -10px;
      align-items: center;
      justify-content: flex-start;
      height: 26px;
      background: linear-gradient(90deg, #ffebeb00 0%, #ffe5e2 100%);
      padding-left: 5px;
      padding-right: 8px;
    }
    &.tradition{
      justify-content: flex-end;
      padding-bottom: 6px;
    }
    .btn {
      height: 20px;
      font-size: 10px;
      margin-left: 4px;
      overflow: hidden;
    }
    .b-red {
      background: linear-gradient(90deg, #ff2929 0%, #ff3d3d 100%);
      color: #FFEBAD !important;
    }
    .b-gray{
      background: #d9d9d9;
      color: #86909c!important;
    }
    .b-gold {
      color: #252729 !important;
    }
    .b-pink{
      background: #ffdede;
      color: #FF5252 !important;
      .angle,.check{
        display: none;
      }
    }
    .angle{
      width: 16px;
      height: 16px;
      background-color: #FFEBAD;
      position: absolute;
      right: -8px;
      bottom: -8px;
      z-index: 1;
      transform: rotate(45deg);
    }
    .check{
      position: absolute;
      right: 0px;
      bottom: -1.2px;
      z-index: 2;
      font-size: 8px;
      font-weight: 700;
    }
    .viewFx{
      height: 26px;
      color: #F96235;
      font-size: 12px;
      display: flex;
      align-items: center;
      position: absolute;
      bottom: 0;
      right: 8px;
      i{
        width: 14px;
        height: 14px;
        border: 1px solid #F96235;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-left: 2px;
      }
      .arrowRight{
        font-size: 10px;
      }
    }
  }
}
</style>
